package com.sun.transaction;

import org.apache.commons.lang3.StringUtils;
import org.apache.rocketmq.client.exception.MQBrokerException;
import org.apache.rocketmq.client.exception.MQClientException;
import org.apache.rocketmq.client.producer.*;
import org.apache.rocketmq.common.message.Message;
import org.apache.rocketmq.common.message.MessageExt;
import org.apache.rocketmq.remoting.exception.RemotingException;

import java.nio.charset.StandardCharsets;
import java.util.concurrent.TimeUnit;

/**
 * 发送同步消息
 */
public class SyncProducer {
    public static void main(String[] args) throws MQClientException, RemotingException, InterruptedException, MQBrokerException {
        //1、创建事务消息生产者producer，并制定生产者组名
        TransactionMQProducer producer = new TransactionMQProducer("group5");
        //2、指定Nameserver地址
        producer.setNamesrvAddr("192.168.32.131:9876;192.168.32.132:9876");

        //添加事务监听器
        producer.setTransactionListener(new TransactionListener() {
            /**
             * 在该方法中执行本地事务
             * @param message
             * @param o
             * @return
             */
            @Override
            public LocalTransactionState executeLocalTransaction(Message message, Object o) {
                if(StringUtils.equals("TAGA",message.getTags())){
                    return LocalTransactionState.COMMIT_MESSAGE;
                }else if(StringUtils.equals("TAGB",message.getTags())){
                    return LocalTransactionState.ROLLBACK_MESSAGE;
                }else if (StringUtils.equals("TAGC",message.getTags())){
                    return LocalTransactionState.UNKNOW;
                }
                return LocalTransactionState.UNKNOW;
            }
            /**
             * 该方法是MQ进行消息事务状态的回查
             * @param messageExt
             * @return
             */
            @Override
            public LocalTransactionState checkLocalTransaction(MessageExt messageExt) {
                System.out.println("消息Tag:" + messageExt.getTags());
                return LocalTransactionState.COMMIT_MESSAGE;
            }
        });

        String[] tags = {"TAGA","TAGB","TAGC"};

        //3、启动producer
        producer.start();
        for (int i = 0; i < 3; i++) {
            //4、创建消息对象，指定主题Topic、Tag和消息体
            /**
             * 参数一：消息的主题Topic
             * 参数二：消息的Tag
             * 参数三：消息内容
             */
            Message msg = new Message("TransactionTopic",tags[i],("Hello World transa："+i).getBytes(StandardCharsets.UTF_8));
            //5、发送消息
            SendResult result = producer.sendMessageInTransaction(msg,null);
            System.out.println("发送详情:"+result);
            //线程睡一秒
            TimeUnit.SECONDS.sleep(1);
        }
        //6、关闭生产者producer
        //producer.shutdown();
    }
}
